<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;

class membersignModel extends Model
{

    protected $table = 'member_sign';
    protected $primaryKey = 'id';
    protected $appends = [];

    // 获取签到记录
    public static function getList ($month) {
        $user = \app\service\auth::getUser();

        if (empty($month) || $month != date('Y-m', strtotime($month))) {
            $month = date('Y-m');
        }

        // 查询指定月份签到记录
        $month_sign_log = self::where('member_id', $user->id)
            ->where('date', 'like', "{$month}-%")
            ->orderBy('id', 'desc')
            ->get();
        $sign_dates = array_column($month_sign_log->toArray(), 'date');

        // 今天的日期
        $today = date('Y-m-d');

        // 计算当月每一天签到情况
        $days = [];
        $month_days = date('t', strtotime($month . '-01'));
        for($i = 1; $i <= $month_days; $i++) {
            $for_date = "{$month}-" . str_pad($i, 2, '0', STR_PAD_LEFT);
            $for_time = strtotime($for_date);

            if ($for_date < $today) {
                $current = 'before';
            } elseif ($for_date == $today) {
                $current = 'today';
            } else {
                $current = 'after';
            }

            $days[] = [
                'is_sign' => in_array($for_date, $sign_dates),      // 判断循环的日期，是否在查询的签到记录里面
                'date' => $for_date,
                'time' => $for_date,
                'day' => $i,
                'week' => date('w', $for_time),
                'current' => $current
            ];
        }
        $result = ['days' => $days];

        // 当月连续签到天数
        $continue_days = 0;
        if ($month != date('Y-m')) {
            $month = date('Y-m');
            $month_sign_log = self::where('member_id', $user->id)
                ->where('date', 'like', "{$month}-%")
                ->orderBy('id', 'desc')
                ->get();
        }
        $yesterday = date('Y-m-d', strtotime($today) - 86400);
        foreach ($month_sign_log as $log) {
            if (!isset($mark_day)) {
                if (in_array($log->date, [$today, $yesterday])) {
                    $continue_days++;
                } else {
                    break;
                }
            } else {
                if ($log->date == $mark_day) {
                    $continue_days++;
                } else {
                    break;
                }
            }
            $mark_day = date('Y-m-d', strtotime($log->date) - 86400);
        }
        $result['cuntinue_days'] = $continue_days;

        return $result;
    }


    // 添加浏览记录
    public static function sign($params) {
        $user = \app\service\auth::getUser();

        $score = DB::transaction(function () use ($user, $params) {

            // 当前时间戳，避免程序执行中间，刚好跨天
            $today = date('Y-m-d');
            $sign = self::where('member_id', $user->id)->orderBy('id', 'desc')->lockForUpdate()->first();
            if ($sign && $sign->date == $today) {
                throw new Exception('您今天已经签到，明天再来吧');
            }

            // 获取积分规则
            $everyday = 5;
            $inc_value = 0;

            // 查询签到记录，判断连续签到天数
            $month = substr($today, 0, 7);
            $signs = self::where('member_id', $user->id)
                ->where('date', 'like', "{$month}-%")
                ->orderBy('id', 'desc')
                ->get();

            $yesterday = date('Y-m-d', strtotime($today) - 86400);

            $continue_days = 0;
            foreach ($signs as $sign) {
                if (!isset($mark_day)) {
                    if ($sign->date == $yesterday) {
                        $continue_days++;
                    } else {
                        break;
                    }
                } else {
                    if ($sign->date == $mark_day) {
                        $continue_days++;
                    } else {
                        break;
                    }
                }
                $mark_day = date('Y-m-d', strtotime($sign->date) - 86400);
            }

            // 计算今天应得积分 $everyday + (($continue_days - 1) * $inc_value)
            $score = $everyday;
            if ($continue_days > 1) {
                $until_add = ($continue_days - 1) * $inc_value;
                if ($until_add > 0) {
                    $score += $until_add;
                }
            }

            // 插入签到记录
            $sign_id = self::insertGetId([
                'member_id' => $user->id,
                'date' => $today,
                'score' => $score >= 0 ? $score : 0,
                'is_replenish' => 0,
                'created_at' => timestamp(),
            ]);

            // 赠送积分
            if ($score > 0) {
                memberModel::score($score, $user->id, 'signin', $sign_id, '签到赠送积分');
            }

            return $score;
        });

        return $score;
    }
}
